package org.example;


import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;

import org.springframework.web.client.RestTemplate;

import java.util.Collection;
import java.util.Map;


//  目前只有一个初始化注册并获取服务的功能
public class DiscoveryService {


    @Autowired
    private CustomConfig customConfig;

    @Autowired
    private RestTemplate restTemplate;


    //这里只需要返回Map即可 自己负责加到并发map      请求nacos服务器 更新这里的map 然后返回
    public Map<String, Collection<ServiceInstance> > registerAndGetServices() {
        String url = "http://" + customConfig.getServerAddr() + "/nacos/registerListener";

        url += "?ip=" + "127.0.0.1" + "&port=" + customConfig.getPort();

        System.out.println("开始发送请求获取列表: " + url);

        // 这里显示指定他反序列化的类型 不然对象会变成linkedHashmap
        ResponseEntity<Map<String, Collection<ServiceInstance> > > response = restTemplate.exchange(
                url,
                HttpMethod.POST,
                null,
                new ParameterizedTypeReference< Map<String, Collection<ServiceInstance> >>() {
                }
        );


        return response.getBody();
    }
}
